package api

import (
	"api/config"
	"api/internal/api/request"
	"api/internal/api/response"
	"api/internal/handler"
	"common/consulinit"
	"flag"
	"github.com/gin-gonic/gin"
	"strconv"
	pb "test_paper_srv/proto"
)

var (
	paperAddress = config.ServerConfigs.PaperSrv.Host + ":" + strconv.Itoa(config.ServerConfigs.PaperSrv.Port)
	paperServer  = flag.String(config.ServerConfigs.PaperSrv.Name, paperAddress, "The server address")
	paperSrv     = handler.NewClient().PaperServer(paperServer)
)

func RegisterPaperService() {
	consulinit.NewConsulClient("117.27.231.112", 8500).RegisterConsul(config.ServerConfigs.PaperSrv.Name, []string{"server"},
		config.ServerConfigs.PaperSrv.Port, config.ServerConfigs.QuestionSrv.Host)
}

func CreatePaper(c *gin.Context) {
	RegisterPaperService()
	var json *request.CreatePaper
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	value, _ := c.Get("userId")
	s, _ := strconv.Atoi(value.(string))
	paper, err := paperSrv.CreatePaper(c, &pb.CreatePaperRequest{
		UserId:        int64(s),
		TestPaperName: json.TestPaperName,
		ClassName:     json.ClassName,
		QuestionId:    json.QuestionId,
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "试卷创建成功", paper)
}

func UpdatePaper(c *gin.Context) {
	RegisterPaperService()
	var json *request.UpdatePaper
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	value, _ := c.Get("userId")
	s, _ := strconv.Atoi(value.(string))
	paper, err := paperSrv.UpdatePaper(c, &pb.UpdatePaperRequest{
		UserId:        int64(s),
		TestPaperName: json.TestPaperName,
		ClassName:     json.ClassName,
		QuestionId:    json.QuestionId,
		PaperId:       int64(json.PaperId),
		OldQuestionId: int64(json.OldQuestionId),
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "试卷修改成功", paper)
}

func DeletePaper(c *gin.Context) {
	RegisterPaperService()
	var json *request.DeletePaper
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	paper, err := paperSrv.DeletePaper(c, &pb.DeletePaperRequest{PaperId: int64(json.PaperId)})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "试卷删除成功", paper)
}
